<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\models\business\BusinessBackpig;
use common\models\business\BusinessPerson;
use common\models\business\BusinessPigPriceDetail;
use common\models\business\BusinessPigPriceType;
use common\models\business\BusinessPigPriceUnit;
use Yii;
use common\models\business\BusinessPigPrice;
use backend\modules\business\models\BusinessPigPriceSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PigPriceController implements the CRUD actions for BusinessPigPrice model.
 */
class PigPriceController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessPigPrice models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessPigPriceSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessPigPrice model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        //分割类型
        $type = BusinessPigPriceType::find()->asArray()->all();
        //销售单位
        $unit = BusinessPigPriceUnit::find()->asArray()->all();

        return $this->render('view', [
            'model' => $this->findModel($id),
            'type' => $type,
            'unit' => $unit
        ]);
    }

    /**
     * Creates a new BusinessPigPrice model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessPigPrice();

        if ($model->load(Yii::$app->request->post())) {

            $model->personid = 0;
            $pmodel = BusinessPig::findOne($model->pigid);
            $model->pigno = $pmodel?$pmodel->no:'';
            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }
            $postdata = Yii::$app->request->post();
            if(!empty($postdata['type'])){



                //新增
                foreach ($postdata['type'] as $key => $row){
                    $idata = [
                        'type' => $row,
                        'price' => $postdata['price'][$key],
                        'unit' => $postdata['unit'][$key],
                        'weight' => $postdata['weight'][$key],
                        'otherdesc' => $postdata['otherdesc'][$key],
                        'pigid' => $model->pigid,
                        'pigpriceid' => $model->id,
                        'createtime' => time(),
                    ];
                    Yii::$app->db->createCommand()->insert(BusinessPigPriceDetail::tableName(),$idata)->execute();
                }
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            //分割类型
            $type = BusinessPigPriceType::find()->asArray()->all();
            //销售单位
            $unit = BusinessPigPriceUnit::find()->asArray()->all();
            return $this->render('create', [
                'model' => $model,
                'type' => $type,
                'unit' => $unit
            ]);
        }
    }

    /**
     * Updates an existing BusinessPigPrice model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

//        var_dump(Yii::$app->request->post());exit;

        if ($model->load(Yii::$app->request->post())) {
            $pmodel = BusinessPig::findOne($model->pigid);
            $model->pigno = $pmodel?$pmodel->no:'';
            $personmodel = BusinessPerson::findOne($model->personid);
            $model->person = $personmodel?$personmodel->name:Yii::$app->user->identity->username;
            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }
            $postdata = Yii::$app->request->post();
            $offset = 0;
            if(!empty($postdata['type'])){
                //删除删除de
                $dids = (new Query())->select('id')
                    ->from(BusinessPigPriceDetail::tableName())
                    ->where('pigpriceid=:id',[':id'=>$model->id])
                    ->all();
                if(!empty($dids)){
                    $ids = ArrayHelper::getColumn($dids,'id');
                    $postid = empty($postdata['id'])?[]:$postdata['id'];
                    $delid = array_diff($ids,$postid);
                    if(!empty($delid)){
                        $ids = implode(',',$delid);
                        Yii::$app->db->createCommand()->delete(BusinessPigPriceDetail::tableName(),'id in (:id)',[':id'=>$ids])->execute();
                    }
                }


                if(!empty($postdata['id'])){        //更新
                    $offset = count($postdata['id'])-1;
                    foreach ($postdata['id'] as $key => $row){
                        $udata = [
                            'type' => $postdata['type'][$key],
                            'price' => $postdata['price'][$key],
                            'unit' => $postdata['unit'][$key],
                            'weight' => $postdata['weight'][$key],
                            'otherdesc' => $postdata['otherdesc'][$key],
                            'pigid' => $model->pigid,
                            'pigpriceid' => $model->id,
                            'createtime' => time(),
                        ];
                        Yii::$app->db->createCommand()->update(BusinessPigPriceDetail::tableName(),$udata,'id=:id',[':id'=>$row])->execute();
                    }
                }

                //新增
                foreach ($postdata['type'] as $key => $row){
                    if($key<=$offset){
                        continue;
                    }
                    $idata = [
                        'type' => $row,
                        'price' => $postdata['price'][$key],
                        'unit' => $postdata['unit'][$key],
                        'weight' => $postdata['weight'][$key],
                        'otherdesc' => $postdata['otherdesc'][$key],
                        'pigid' => $model->pigid,
                        'pigpriceid' => $model->id,
                        'createtime' => time(),
                    ];
                    Yii::$app->db->createCommand()->insert(BusinessPigPriceDetail::tableName(),$idata)->execute();
                }
            }
            return $this->redirect(['view', 'id' => $model->id]);
        }  else {
            //分割类型
            $type = BusinessPigPriceType::find()->asArray()->all();
            //销售单位
            $unit = BusinessPigPriceUnit::find()->asArray()->all();
            return $this->render('update', [
                'model' => $model,
                'type' => $type,
                'unit' => $unit
            ]);
        }
    }

    /**
     * Deletes an existing BusinessPigPrice model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessPigPrice model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessPigPrice the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessPigPrice::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @param $pigid
     * @return string
     * 根据选定的仔猪，取出仔猪的毛重
     */
    public function actionSearchGweight($pigid)
    {
        $gweight = BusinessBackpig::find()->select('grossweight')->where('pigid=:id',[':id'=>$pigid])->asArray()->scalar();

        return json_encode(['data'=>$gweight]);
    }
}
